<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-04 14:51:01
 * @Last Modified time: 2023-02-20 11:06:55
 */
namespace app\api\controller\store;	
use think\facade\App;
use app\common\services\store\OrderService;
use app\common\services\store\order\CheckoutService;
use app\common\services\user\UserAddressService;
use app\common\services\store\ShopService;
use app\common\services\store\CartService;
use frank\services\CacheService;
/**
 * Class Order
 */
class Order extends \app\api\controller\Base
{ 	
    /**
     * OrderService constructor.
     * @param App $app
     */
    public function __construct(App $app,OrderService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 获取订单详细
     * @force(false)
     * @method(GET)
     */
    public function detail(){
        $id = $this->request->param('id');
        $detail = $this->service->getOrderDetail($id);
        $this->success($detail);
    }

    /**
     * 获取订单详细
     * @method(GET)
     */
    public function userDetail(){
        $id = $this->request->param('id');
        $this->success($this->service->getUserOrderDetail($id,$this->uid));
    }


    /**
     * 获取订单支付结果
     * @method(GET)
     */
    public function payResult(){
        $id = $this->request->param('id');
        $this->success($this->service->getOrderDetail($id,[]));
    }


    /**
     * 订单结算提交的参数
     */
    private function getParam($define = [])
    {
        return array_merge($define, $this->request->param());
    }

    /**
     * 直接下单
     * @method(GET)
     */
    public function buyNow(){
        $cache = CacheService::instance();
        $time = time();
        $count = $cache->getTokenBucket('count:'.$time);
        if(!$count){
            $count = 1;
        }
        $count++;
        $cache->setTokenBucket('count:'.$time,$count);
    	// 结算台服务
        $checkout = CheckoutService::instance();
        // 订单结算api参数
        $params = $checkout->setParam($this->getParam([
            'goods_id' => 0,
            'goods_num' => 0,
            'goods_sku_id' => ''
        ]));

        //获取商品列表
        $orderData = $this->service->getOrderByNow(
            $this->uid,
            $params['goods_id'],
            $params['goods_sku_id'],
            $params['goods_num']
        );

        if(!$orderData) $this->error($this->service->getError());
        // 获取订单确认信息
        $orderInfo = $checkout->onCheckout($this->user, $orderData);
        if($checkout->hasError()) $this->error($checkout->getError()?:'订单未知错误',$orderInfo);
        
        if ($this->request->param('now_buy') == '1' ) {
            $orderInfo['address_list'] = UserAddressService::instance()->getUserAddressSelect([
                'user_id'=>$this->uid
            ]);
            $orderInfo['shop_list'] = ShopService::instance()->getShopSelect();
            $this->success('获取成功',$orderInfo);
        }

        // 创建订单
        if (!$checkout->createOrder($orderInfo, $params)) {
            $this->error($checkout->getError() ?: '订单创建失败');
        }

        // 构建支付请求
        $payment = $checkout->onOrderPayment($this->user, $params['pay_type']);
        $order = $checkout->getOrder();
        $this->success('获取成功',[
            'order_no' => $order['order_no'],
            'order_id' => $order['id'],
            'payment' => $payment// 微信支付参数
        ]);
    }


    /**
     * 订单确认-购物车结算
     */
    public function cart()
    {
        // 实例化结算台服务
        $checkout = CheckoutService::instance();
        // 订单结算api参数
        $params = $checkout->setParam($this->getParam([
            'cart_ids' => '',
        ]));
        // 商品结算信息
        $cartService = CartService::instance()->init($this->user);
         // 购物车商品列表
        $goodsList = $cartService->getList($params['cart_ids']);
        if(empty($goodsList)) $this->error('购物车没有商品哦');
        // 获取订单结算信息
        $orderInfo = $checkout->onCheckout($this->user, $goodsList);
        if ($this->request->param('now_buy') == '1') {
            $orderInfo['address_list'] = UserAddressService::instance()->getUserAddressSelect([
                'user_id'=>$this->uid
            ]);
            $orderInfo['shop_list'] = ShopService::instance()->getShopSelect();
            $this->success('获取成功',$orderInfo);
        }
        // 订单结算提交
        if ($checkout->hasError()) {
            return $this->error($checkout->getError());
        }
        // 创建订单
        if (!$checkout->createOrder($orderInfo, $params)) {
           return  $this->error($checkout->getError() ?: '订单创建失败');
        }
        // dump($Checkout->payData);die;
        // 构建微信支付请求
        $payment = $checkout->onOrderPayment($this->user, $params['pay_type']);
        $order = $checkout->getOrder();
        // 移出购物车中已下单的商品
        $cartService->clearAll($params['cart_ids']);
        $this->success('获取成功',[
            'order_no' => $order['order_no'],
            'order_id' => $order['id'],
            'payment' => $payment// 微信支付参数
        ]);
    }

}